#include <bsp_pwm.h>

#include "string.h"

void PWM_init(PWM *pwm, TIM_HandleTypeDef *pwm_htim, uint32_t tim_channel) {
    // 写入PWM配置
    pwm->pwm_htim = pwm_htim;
    pwm->tim_channel = tim_channel;

    // 设置PWM的计数周期
    pwm->tim_period = pwm_htim->Init.Period;

    // 设置PWM的计数器通道
    HAL_TIM_PWM_Start(pwm->pwm_htim, pwm->tim_channel);
}

void PWM_set_duty(PWM *pwm, uint32_t duty) {
    __HAL_TIM_SET_COMPARE(pwm->pwm_htim, pwm->tim_channel, duty);
}

void PWM_set_duty_percent(PWM *pwm, float duty_percent) {
    uint32_t duty = (duty_percent / 100.0f) * pwm->tim_period;
    __HAL_TIM_SET_COMPARE(pwm->pwm_htim, pwm->tim_channel, duty);
}

void PWM_set_full(PWM *pwm) {
    __HAL_TIM_SET_COMPARE(pwm->pwm_htim, pwm->tim_channel, pwm->tim_period);
}

void PWM_set_zero(PWM *pwm) {
    __HAL_TIM_SET_COMPARE(pwm->pwm_htim, pwm->tim_channel, 0);
}
